<template>
  <div class="menu">
    <div class="toolbar">
      <a-button type="primary" @click="showModal(null)">新增路由</a-button>
    </div>

    <a-table :columns="columns" :data="menuItems" v-model:expandedKeys="expandedKeys">
      <template #optional="{ record }">
        <!-- 新增调试信息 -->
          <div style="display: flex;">
            <a-button type="primary" @click="showModal(record)">编辑</a-button>
            <a-button type="primary" @click="handleDelete(record.id)">删除</a-button>
          </div>
          <a-modal :visible="visible" @ok="handleDelete(record.id)" @cancel="handleCancel">
            <template #title>
              删除用户
            </template>
            <div>确定删除该用户吗</div>
          </a-modal>

        </template>
    </a-table>
    <!-- 新增/编辑弹窗 -->
    <a-modal
        v-model:visible="modalVisible"
        :title="currentRow ? '编辑路由' : '新增路由'"
        @ok="handleSubmit"
    >
      <a-form ref="formRef" :label-col="{ span: 6 }" :model="formState">
        <a-form-item :rules="[{ required: true, message: '请输入路由名称' }]" label="路由名称"
                     name="menuName">
          <a-input v-model ="formState.menuName"/>
        </a-form-item>

        <a-form-item :rules="[{ required: true, message: '请输入路由路径' }]" label="路由路径" name="Path">
          <a-input v-model="formState.path"/>
        </a-form-item>

        <a-form-item label="路由类型" name="menuType">
          <a-select v-model="formState.menuType">
            <a-option value="NAV">导航路由</a-option>
            <a-option value="DIR">目录路由</a-option>
            <a-option value="MENU">菜单路由</a-option>
          </a-select>
        </a-form-item>

        <a-form-item
            label="请选择父节点"
            name="path"
            :rules="[{ required: true, message: '请选择父节点' }]"
        >
          <a-select
              v-model="formState.parentId"
          >
            <a-option
                v-for="dir in options.data"
                :key="dir.id"
                :value="dir.id"
            >
              {{ dir.menuName }}
            </a-option>
          </a-select>
        </a-form-item>

        <a-form-item label="图标" name="icon">
          <a-input v-model="formState.icon" @focus="iconDialogVisible = true"/>
        </a-form-item>
      </a-form>

      <icon-selector v-model="formState.icon" v-model:visible="iconDialogVisible" />

    </a-modal>

  </div>
</template>

<script setup>
import {onMounted, reactive, ref,watch} from 'vue'
import {securityAPI} from "@/api/security/index.js"
import {Message} from "@arco-design/web-vue";
import IconSelector from "@/views/common/IconSelector.vue";

const menuItems = ref([])
const modalVisible = ref(false)
const currentRow = ref(null)
const formRef = ref()
const iconDialogVisible = ref(false)

const expandedKeys = ref([]);

const formState = reactive({
  menuName: '',
  menuId: '',
  path: '',  // 统一字段命名
  menuType: 'NAV',
  icon: '',
  parentId:null,
  permId:'p1',
  hidden:false,
  sort:"3"
})

// 列配置增加操作列
const columns = [
  {title: '路由名称', dataIndex: 'menuName'},
  {title: '路由路径', dataIndex: 'path'},
  {title: '路由类型', dataIndex: 'menuType'},
  {title: '图标', dataIndex: 'icon'},
  {title: '操作', key: 'action', width: 200,slotName: 'optional'}
]

// 显示弹窗
const showModal = (record) => {
  currentRow.value = record
  modalVisible.value = true
  if (record) {
    formState.menuId = record.menuId || record.id || ''  // 兼容不同ID字段名
    formState.menuName = record.menuName || ''
    formState.path = record.path || ''
    formState.menuType = record.menuType || 'NAV'
    formState.parentId = Number(record.parentId) || null
    formState.icon = record.icon || ''
  } else {
    formRef.value?.resetFields()
    formState.menuId = ''
  }

}

watch(() => formState.menuType, (newVal) => {
      loadDirectories()
})

watch(() => formState.parentId, (newVal) => {
  console.log('formState.parentId:', formState.parentId)
  console.log('currentRow.value:', currentRow.value)
})

//目录路由
const options = reactive({
  data:[]
})

const loadDirectories = () => {
  try {
    options.data = []
    formState.parentId = ''
    //请根据 menuType 获取到父节点
    if (formState.menuType === 'DIR') {
      options.data = menuItems.value.filter(item => item.menuType === 'NAV')
    }

    if (formState.menuType === 'MENU') {
      menuItems.value.forEach(item => {
        const temp =  item.children.filter(child => child.menuType === 'DIR')
        //合并数组
        options.data = options.data.concat(temp)
      })
    }
  } catch (error) {
    console.error('获取目录失败:', error)
  }
}


// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    const api = currentRow.value
        ? securityAPI.updateMenu
        : securityAPI.addMenu

    // 构造符合接口要求的参数对象
    const formState2 = {
      ...formState,
      menuId: formState.menuId,
      // 目录类型需要额外处理路径格式
      path: formState.menuType === 'DIR' ?
          `${formState.path}` :
          formState.path,
      parentId: formState.parentId || 0
    }

    await api(formState2)
    modalVisible.value = false
    getMenuItems()
  } catch (error) {
    console.error('操作失败:', error)
  }
}
// 删除路由
const handleDelete = async (id) => {
  try {
    console.log('id',id)
    await securityAPI.deleteMenu(id)
    getMenuItems()
  } catch (error) {
    console.error('删除失败:', error)
    Message.error('删除失败')
  }
}
// 取消删除
const handleCancel = () => {
  modalVisible.value = false
}

// 获取菜单数据
const getMenuItems = () => {
  securityAPI.getMenu().then(res => {
    menuItems.value = res.data
  })
}

onMounted(() => {
  getMenuItems()
})
</script>

<style scoped>
.toolbar {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}
</style>